package log

import (
	"errors"
	"log"
)

type ConfFileWriter struct {
	On              bool   `toml:"On"`
	LogPath         string `toml:"LogPath"`       // 当前执行写入的日志文件名
	RotateLogPath   string `toml:"RotateLogPath"` // 轮转日志名格式
	WfLogPath       string `toml:"WfLogPath"`     // WARNING、ERROR 级别的日志存到其它文件
	RotateWfLogPath string `toml:"RotateWfLogPath"`
}

type ConfConsoleWriter struct {
	On    bool `toml:"On"`
	Color bool `toml:"Color"`
}

type LogConf struct {
	Level   string            `toml:"LogLevel"`      // 日志开关级别
	Tracing bool              `toml:"tracing"`       // 是否记录调用栈
	FW      ConfFileWriter    `toml:"FileWriter"`    // 写到文件
	CW      ConfConsoleWriter `toml:"ConsoleWriter"` // 写到控制台
}

// SetupLogInstanceWithConf 用配置将日志初始化
func SetupLogInstanceWithConf(lc LogConf, logger *Logger) (err error) {
	if lc.FW.On {
		// 普通日志存到文件
		if len(lc.FW.LogPath) > 0 {
			w := NewFileWriter()
			w.SetFileName(lc.FW.LogPath)
			err = w.SetPathPattern(lc.FW.RotateLogPath)
			if err != nil {
				log.Println("SetupLogInstanceWithConf SetPathPattern err: ", err)
				return err
			}
			w.SetLogLevelFloor(TRACE)
			if len(lc.FW.WfLogPath) > 0 {
				w.SetLogLevelCeil(INFO)
			} else {
				w.SetLogLevelCeil(ERROR)
			}
			logger.Register(w)
		}

		// WARNING、ERROR 级别的日志存到其它文件
		if len(lc.FW.WfLogPath) > 0 {
			wfw := NewFileWriter()
			wfw.SetFileName(lc.FW.WfLogPath)
			err = wfw.SetPathPattern(lc.FW.RotateWfLogPath)
			if err != nil {
				log.Println("SetupLogInstanceWithConf SetPathPattern err: ", err)
				return err
			}
			wfw.SetLogLevelFloor(WARNING)
			wfw.SetLogLevelCeil(ERROR)
			logger.Register(wfw)
		}
	}

	if lc.CW.On {
		w := NewConsoleWriter()
		w.SetColor(lc.CW.Color)
		logger.Register(w)
	}
	switch lc.Level {
	case "trace":
		logger.SetLevel(TRACE)
	case "debug":
		logger.SetLevel(DEBUG)
	case "info":
		logger.SetLevel(INFO)
	case "warning":
		logger.SetLevel(WARNING)
	case "error":
		logger.SetLevel(ERROR)
	case "fatal":
		logger.SetLevel(FATAL)
	default:
		err = errors.New("invalid log level")
	}

	logger.SetTracing(lc.Tracing)
	return
}

func SetupDefaultLogWithConf(lc LogConf) (err error) {
	defaultLoggerInit()
	return SetupLogInstanceWithConf(lc, loggerDefault)
}
